#include "string.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
  int id;
  char name[16];
  struct Node *LChild, *RChild;
} BiTNode, *BiTree;

void emptyBlankLine() {
  while (getchar() != '\n') {
    continue;
  }
}

void insertBit(BiTree *current, int id, char *name) {
  BiTNode *s;
  if (!*current) {
    s = (BiTNode *)malloc(sizeof(BiTNode));
    s->id = id;
    strcpy(s->name, name);
    s->LChild = NULL;
    s->RChild = NULL;
    *current = s;
  } else {
    if (id < (*current)->id) {
      insertBit(&(*current)->LChild, id, name);
    } else {
      if (id >= (*current)->id) {
        insertBit(&(*current)->RChild, id, name);
      }
    }
  }
}

BiTree createTree() {
  int id, index, length;
  char name[16];
  BiTree root = NULL;
  printf("创建二叉树,请输入节点的总数量:");
  scanf("%d", &length);
  emptyBlankLine();
  for (index = 0; index < length; index++) {
    printf("输入第%d个节点:\n", index + 1);
    printf("学号:");
    scanf("%d", &id);
    emptyBlankLine();
    printf("姓名:");
    scanf("%s", name);
    emptyBlankLine();
    insertBit(&root, id, name);
  }
  return root;
}

void inOrder(BiTree root) {
  if (root) {
    inOrder(root->LChild);
    printf("学号:%4d姓名:%6s\n", root->id, root->name);
    inOrder(root->RChild);
  }
}

BiTNode *findItem(BiTree current, int id) {
  if (current) {
    if (current->id > id) {
      return findItem(current->LChild, id);
    } else if (current->id < id) {
      return findItem(current->RChild, id);
    }
    return current;
  } else {
    return NULL;
  }
}

int main(void) {
  int choose, id;
  BiTNode *res;
  BiTree root = createTree();
  while (!(choose = 0)) {
    puts("请选择要执行的操作");
    puts("1.升序查看学生数据\t2.按学号查找学生数据\n"
         "3.退出");
    scanf("%d", &choose);
    switch (choose) {
    case 1:
      inOrder(root);
      break;
    case 2:
      printf("输入查找的学号:");
      scanf("%d", &id);
      emptyBlankLine();
      res = findItem(root, id);
      printf("学号:%4d姓名:%6s\n", res->id, res->name);
      break;
    case 3:
      exit(0);
      break;
    default:
      puts("请输入正确的指令!");
    }
  }
  return false;
}
